import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/user_center/coupon_item_entity.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';

///优惠券控制器
class CouponController extends BaseController {
  RxList<CouponItemEntity?>? couponList = <CouponItemEntity>[].obs;
  var dataList = [].obs;
  var page=1.obs;
  TextEditingController codetxtController = TextEditingController();

  bool hasNextPage = true;

  @override
  void onInit() {
    getCanReceiveCouponList();
    super.onInit();
  }

  //获取可领取优惠券列表
  Future getCanReceiveCouponList() async {
    Tools.showLoading();
  return  Network.getCanReceiveCouponList(page.value,10).then((value) {
      hasNextPage = value!.hasNextPage!;
      couponList?.value = value.list!;
      Tools.hideLoading();
    }).catchError((error){
      Tools.hideLoading();
    });
  }


  ///领券
  Future receiveCoupon(String couponId) async{
    // print(couponId);
    Tools.showLoading();
    Network.receiveCoupon(couponId).then((value){
      // print(value);
      if(value==true){
        Tools.showToast("领券成功");
        getCanReceiveCouponList();//重新加载可领列表
        Tools.hideLoading();
      }
      
    }).catchError((error){
      Tools.hideLoading();
    });
  }


  ///兑换
  Future exchange() async{
    if(codetxtController.text==''){
      Tools.showToast("请先输入兑换码");
    }else{
      Tools.showLoading();
      Network.exchangeCoupon(codetxtController.text).then((value){
        if(value==true){
          Tools.showToast("兑换成功");
          getCanReceiveCouponList();//重新加载可领列表
          Tools.hideLoading();
        }
      }).catchError((error){
        Tools.hideLoading();
      });
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    await getCanReceiveCouponList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading()async {
    super.onPageLoading();
    if(hasNextPage){
      page.value+=1;
      await getCanReceiveCouponList();
      baseRefreshCtr.loadComplete();
    }
  }
}
